package member

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model/input/adminin"
	"hotgo/internal/service"
	"hotgo/utility/tree"

	"hotgo/api/api/member/v1"
)

func (c *ControllerV1) UpdateInfo(ctx context.Context, req *v1.UpdateInfoReq) (res *v1.UpdateInfoRes, err error) {

	if req.Nickname == "" && req.Avatar == "" && req.EncryptedData == "" && req.Iv == "" {
		return
	}

	infoInp := &adminin.MemberUpdateInfoInp{
		ID:       contexts.GetUserId(ctx),
		Nickname: req.Nickname,
		Avatar:   req.Avatar,
	}

	if req.EncryptedData != "" && req.Iv != "" {
		mini, err := wechat.DecryptData(ctx, contexts.GetSessionKey(ctx), req.EncryptedData, req.Iv)
		if err != nil {
			return nil, gerror.New("修改失败")
		}
		mb, err := service.AdminMember().GetByMobile(ctx, mini.PhoneNumber, consts.RoleAllUser)
		if mb != nil && mb.Id != 0 {
			return nil, gerror.New("手机号已绑定")
		}
		infoInp.Mobile = mini.PhoneNumber
	}

	if infoInp.Nickname != "" || infoInp.Avatar != "" || infoInp.Mobile != "" {
		err = service.AdminMember().UpdateInfo(ctx, infoInp)
		if err != nil {
			return nil, gerror.New("修改失败")
		}
	}

	return
}

// 用户轮播动态信息
func (c *ControllerV1) CarouselDynamic(ctx context.Context, req *v1.CarouselDynamicReq) (res *v1.CarouselDynamicRes, err error) {
	list, err := service.SysUserOrder().CarouselDynamic(ctx)
	if err != nil {
		return
	}
	res = new(v1.CarouselDynamicRes)
	res.List = list
	return
}

// 团队人数
func (c *ControllerV1) TeamCount(ctx context.Context, req *v1.TeamCountReq) (res *v1.TeamCountRes, err error) {

	// 获取用户信息
	mb, err := service.AdminMember().GetById(ctx, &adminin.GetByIdInp{
		Id: contexts.GetUserId(ctx),
	})
	if err != nil {
		return nil, gerror.New("获取用户信息失败")
	}

	res = new(v1.TeamCountRes)

	// 直接分享人数
	res.Direct, err = dao.AdminMember.Ctx(ctx).Where(dao.AdminMember.Columns().Pid, contexts.GetUserId(ctx)).Count()
	// 间接分享人数
	res.Indirect, err = dao.AdminMember.Ctx(ctx).
		WhereNot(dao.AdminMember.Columns().Pid, contexts.GetUserId(ctx)).
		WhereLike(dao.AdminMember.Columns().Tree, tree.GenLabel(mb.Tree, mb.Id)+"%").Count()

	return
}

func (c *ControllerV1) TeamList(ctx context.Context, req *v1.TeamListReq) (res *v1.TeamListRes, err error) {
	list, totalCount, err := service.AdminMember().TeamList(ctx, &req.TeamListInp)
	res = new(v1.TeamListRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)
	return
}
